<template>
  <div class="audio_play">
    音乐播放界面
    <audio controls ref="audio">
      <source src="../../assets/昼夜 - 雨的印记.mp3" type="audio/mp3" />
    </audio>
    <div class="player_button" @click="playMusic">
          <van-icon v-if="!isPlayer" name="play-circle-o" size="35px" />
          <van-icon v-else name="pause-circle-o" size="35px" />
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted} from "vue";
let audio = document.createElement("audio");
let isPlayer = ref(false);
//获取保存在sessionStorage中的播放时间
let saveTime = sessionStorage.getItem("currentTime");
//播放音乐
function playMusic(){
  isPlayer.value = !isPlayer.value;
  if (isPlayer.value) {
    audio.play();
    //从保存的时间开始播放
    audio.currentTime = saveTime;
    //打印当前播放时间
    console.log(audio.currentTime);
  }
  if (!isPlayer.value) {
    audio.pause();
    //暂停时保存当前播放时间,下次打开时从保存的时间开始播放
    saveTime = audio.currentTime;
    //将保存的时间保存到sessionStorage中并且赋值给currentTime
    sessionStorage.setItem("currentTime", saveTime);
    console.log(saveTime);
  }
}

onMounted(() => {
  //页面加载时自动播放音乐
  //获取保存在sessionStorage中的播放状态
  let state = sessionStorage.getItem("isPlayer");
  if (state === "true") {
    isPlayer.value = true;
    audio.play();
    //从保存的时间开始播放
    audio.currentTime = saveTime;
    //打印当前播放时间
    console.log(audio.currentTime);
  }
});
</script>

<style>
</style>
